/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        if (root == nullptr)return {};
        vector<TreeNode*>q;
        q.push_back(root);
        vector<vector<int>>ans;
        vector<int>res;
        res.push_back(root->val);
        ans.push_back(res);
        while (q.size()) {
            vector<TreeNode*>q1;
            vector<int>res1;
            for (auto x : q) {
                if (x->left) {
                    q1.push_back(x->left);
                    res1.push_back(x->left->val);
                }
                if (x->right) {
                    q1.push_back(x->right);
                    res1.push_back(x->right->val);
                }
            }
            if (!res1.empty()) ans.push_back(res1);
            q = move(q1);
        }
        reverse(ans.begin(), ans.end());
        return ans;
    }
};